import {config, is, sandBox} from '../../../lib/myapp.js'
Page({

    data: {
        phoneCode: {
	        total:60,
	        access_token:null,
	        codeText:'发送'
        },
	    verification : '',
	    sending: false,
        order: {},
        order_no: '',
        channel: 'wx_pub',
        amount: 0,
        loading: false,
        showPay: false,
        type: 'wx_pub_qr',
        wx_pub_qr: '',
        allTypes: [
            {
                type: 'wx_pub_qr',
                text: '微信支付',
                checked: true,
                id: 'wechat_pay',
                desc: '使用微信扫描二维码支付',
                icon: 'icon-weixin'
            },
            {
                type: 'pop_cash_pay',
                text: 'POP支付',
                checked: false,
                id: 'pop_pay',
                desc: '使用门店POS机收银',
                icon: 'icon-yinlianqia'
            },
            {
                type: 'cash_pay',
                text: '现金支付',
                checked: false,
                id: 'cash_pay',
                desc: '使用现金支付',
                icon: 'icon-xianjin'
            },
            {
                type: 'ali_scan_pay',
                text: '支付宝支付',
                checked: false,
                id: 'ali_pay',
                desc: '使用支付宝支付',
                icon: 'icon-zhifubao'
            },
            {
                type: 'balance',
                text: '余额支付',
                checked: false,
                id: 'balance_pay',
                desc: '使用余额支付',
                icon: 'icon-yuexin'
            }
        ],
        current: {
            type: 'wx_pub_qr',
            text: '微信支付',
            checked: true,
            id: 'wechat_pay',
            desc: '使用微信扫描二维码支付',
            icon: 'icon-weixin'
        },
        reCurrent: {
            type: 'wx_pub_qr',
            text: '微信支付',
            checked: true,
            id: 'wechat_pay',
            desc: '使用微信扫描二维码支付',
            icon: 'icon-weixin'
        },
        isRecharge: false,
        isDisparity:false
    },

    onLoad(e){

        this.setData(
            {
                order_no: e.order_no,
                loading: false,
                code: '',
                wx_pub_qr: e.wx_pub_qr,
                isRecharge: !!e.wx_pub_qr,
                isDisparity:!!e.isDisparity,
                allTypes: !!e.wx_pub_qr ? this.data.allTypes.filter(v => v.id !== 'balance_pay') : this.data.allTypes
            }
        )

    },
    onShow(){

        this.queryOrderDetail(this.data.order_no)

        if (this.data.wx_pub_qr) {
            this.getPaymentQrCode(this.data.wx_pub_qr)
        } else {
            this.payment()
        }

    },
    refreshPaymentResult(){
        var oauth = wx.getStorageSync('user_token')
        sandBox.post({
            api: `${this.data.isRecharge ? 'api/O2O/balance/paid' : 'api/O2O/shopping/order/check/pay'}`,
            data: {order_no: this.data.order_no},
            header: {Authorization: oauth},
        }).then((res) => {
            res = res.data
            if(res.data.code == 200) {
                wx.showModal({
                    content:'支付成功',
                    showCancel:false,
                    success:res=>{
                       if (res.confirm) {
                           wx.redirectTo({
                               url:`/pages/order/detail/detail?order_no=${this.data.order_no}`
                           })
                       }
                    }
                })
            }
        })
    },
    queryOrderDetail (order_no) {
        var oauth = wx.getStorageSync('user_token')

        sandBox.get({
            api: this.data.isRecharge ? `api/O2O/balance/detail/${order_no}` : `api/O2O/order/detail/${order_no}`,
            header: {Authorization: oauth},
        }).then(res => {
            res = res.data
            wx.setStorageSync(this.data.isRecharge ? 'recharge_retreat' : 'service_retreat', res.data)

            this.setData({
                order: res.data
            })
        }).catch(rej => {
            wx.showModal({
                title: '获取订单数据失败',
	            showCancel: false
            })
        })
    },
    getPaymentQrCode(url){
        var oauth = wx.getStorageSync('user_token')

        sandBox.post({
            api: 'api/O2O/shopping/order/wx_pub_qr',
            data: {url: url},
            header: {Authorization: oauth},
        }).then(res => {
            res = res.data
            if (res.code == 200 && res.data && res.data.code) {
                var code = 'data:image/svg+xml,' + res.data.code
                this.setData({
                    code: code
                })
            } else {
                wx.showModal({
                    content: res.message || '支付二维码请求失败',
	                showCancel: false
                })
            }
        }).catch(rej => {
            wx.showModal({
                content: '服务端出错',
	            showCancel: false
            })
        })
    },

    payment(){

        if (!this.data.order_no) return;
        var oauth = wx.getStorageSync('user_token')
        sandBox.post({
            api: `api/O2O/shopping/order/charge`,
            data: {
                order_no: this.data.order_no,
                channel: 'wx_pub_qr'
            },
            header: {Authorization: oauth},
        }).then((res) => {
            res = res.data
            if (res.code == 200 && res.data) {
                if (!res.data.credential.wx_pub_qr) {
                    wx.showModal({
                        content: '返回支付链接为空',
	                    showCancel: false
                    })
                    return
                }

                this.getPaymentQrCode(res.data.credential.wx_pub_qr)
            } else {
                wx.showModal({
                    content: res.message || '支付请求失败',
	                showCancel: false
                })
            }
        }).catch(rej => {
            wx.showModal({
                content: '服务端出错',
	            showCancel: false
            })
        })
    },

    changePayType(){

        this.setData({
            showPay: !this.data.showPay
        })
    },

    payType(e){

        var reCurrent = this.data.allTypes.filter(item => {
            return item.type == e.detail.value
        })
        this.setData({
            reCurrent: reCurrent[0],

        })


    },
    submit(){
        if (!this.data.type) {
            wx.showModal({
                content: '未选择支付方式',
	            showCancel: false
            })

            return;
        }
        this.setData({
            type: this.data.reCurrent.type,
            showPay: !this.data.showPay,
            current: this.data.reCurrent
        })


    },
    jump() {

        wx.redirectTo({
            url: `/pages/store/success/success?order_no=${this.data.order_no}&amount=${this.data.amount}&channel = ${this.data.channel}`
        })

    },

    sure(){

        var oauth = wx.getStorageSync('user_token');

        if (this.data.type == 'balance') {
	        if (!is.has(this.data.phoneCode.access_token)) {
		        wx.showModal({
			        title: '',
			        content: '请先获取验证码',
			        showCancel: false
		        });
		        return
	        } else if (!is.has(this.data.verification)) {
		        wx.showModal({
			        title: '',
			        content: '请输入验证码',
			        showCancel: false
		        });
		        return
	        }
        }

        sandBox.post({
            api: `${this.data.isRecharge ? 'api/O2O/balance/amount/pay' : 'api/O2O/shopping/order/amount/pay'}`,
            data: {
                order_no: this.data.order_no,
                channel: this.data.type,
                code: this.data.verification,
	            access_token:this.data.phoneCode.access_token,
	            mobile: this.data.order.user.mobile
            },
            header: {Authorization: oauth},
        }).then(res => {
            res = res.data;
            if (res.code == 200) {
                if (this.data.isDisparity) {

                    var refund_no = wx.getStorageSync('refund_no')
                    wx.redirectTo({
                        url:`/pages/afterSales/complete/complete?refund_no=${refund_no}`
                    })
                } else {
                    wx.redirectTo({
                        url:`/pages/order/detail/detail?order_no=${this.data.order_no}`
                    })
                }

            } else {
                wx.showModal({
                    content:'支付失败',
	                showCancel: false
                })
            }
        }).catch(rej => {
            wx.showModal({
                content:'支付失败',
	            showCancel: false
            })
        })


    },
	random(){
		return Math.random().toString(36).substr(2,24);
	},
	changeCode(e) {
		this.setData({
			verification: e.detail.value
		})
    },
    // 获取手机验证码
    getCode() {
	    if(this.data.sending) return;
	    var randoms = this.random();
	    this.setData({
		    sending:true,
		    'phoneCode.codeText':"发送中",
		    'phoneCode.access_token':randoms
        });
	    this.getLoginCode();
    },
    // 发送验证码
	getLoginCode() {
	    wx.request({
	        url: config.GLOBAL.baseUrl + "api/sms/verify-code",
		    method: 'POST',
            data: {
	            mobile:this.data.order.user.mobile,
	            access_token:this.data.phoneCode.access_token
            },
            success: res => {
	            if (res.statusCode == 200) {
	            	res = res.data;
	                if (res.success) {
		                var total =this.data.phoneCode.total;
		                this.setData({
			                'phoneCode.codeText':total+"秒s"
		                });
		                var timer =setInterval(()=>{
			                total--;
			                this.setData({
				                'phoneCode.codeText':total+"秒s"
			                });
			                if(total<1){
				                this.setData({
					                sending:false,
					                'phoneCode.codeText':"发送"
				                });
				                clearInterval(timer);
			                }
		                },1000);
                    } else {
		                wx.showModal({
			                title: '',
			                content: res.message,
			                showCancel: false
		                });
		                this.setData({
			                sending:false,
			                'phoneCode.codeText':"发送"
		                });

                    }
                } else {
		            wx.showModal({
			            title: '',
			            content: "请求失败",
			            showCancel: false
		            });
		            this.setData({
			            sending:false,
			            'phoneCode.codeText':"发送"
		            });
                }
            }
        })
    },

})